<template>
    <div>
        <breadcrumb></breadcrumb>
        <div class="main">
            <h3 class="title">
                {{ $route.query.categoryId ? '编辑车辆' : '新增车辆' }}
            </h3>
            <div class="formBox">
                <el-form class="formStyle" status-icon :model="vehicleForm" :rules="rules" ref="vehicleForm"
                    label-width="120px">
                    <el-form-item label="车辆照片" prop="name" class="picFormItem">
                        <el-upload class="avatar_uploader" :action="url" :show-file-list="false" :headers="headers"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">

                            <el-image v-if="vehicleForm.image" :src="vehicleForm.image" class="VehiclePic" :fit="'contain'">
                            </el-image>
                            <div v-else class="uploadIconBox">
                                <div class="iconfontcolor icon-a-"></div>
                                <span class="text">上传图片</span>
                            </div>
                        </el-upload>
                        <div class="prompt">
                            提示<br>
                            1、请上传小于5M的图片<br>
                            2、为了页面的美观，建议上传背景为透明的png格式图片
                        </div>
                        <div class="picBox">
                            <el-image v-if="vehicleForm.image != ''" class="pic" :src="vehicleForm.image"
                                :preview-src-list="[vehicleForm.image]" :fit="'contain'">
                            </el-image>
                        </div>
                    </el-form-item>
                    <el-col :span="6">
                        <el-form-item label="车辆名称" prop="name">
                            <el-input size="small" v-model="vehicleForm.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="车辆简称" prop="simpleName">
                            <el-input size="small" v-model="vehicleForm.simpleName"></el-input>
                        </el-form-item>
                    </el-col>


                    <div class="layoutBox">
                        <el-form-item label="厢长" prop="length" class="layout">
                            <el-input placeholder="" v-model="lengthStart" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">米</template>
                            </el-input>
                            <span class="layout_middle">至</span>
                            <el-input placeholder="" v-model="lengthEnd" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">米</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="载方" prop="capacity" class="layout">
                            <el-input placeholder="" v-model="capacityStart" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">方</template>
                            </el-input>
                            <span class="layout_middle">至</span>
                            <el-input placeholder="" v-model="capacityEnd" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">方</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="载重" prop="loads" class="layout">
                            <el-input placeholder="" v-model="loadsStart" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">吨</template>
                            </el-input>
                            <span class="layout_middle">至</span>
                            <el-input placeholder="" v-model="loadsEnd" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">吨</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="车高" prop="height" class="layout">
                            <el-input placeholder="" v-model="heightStart" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">米</template>
                            </el-input>
                            <span class="layout_middle">至</span>
                            <el-input placeholder="" v-model="heightEnd" onkeyup="value=value.replace(/[^\d.]/g,'')"
                                class="layout_item" size="small">
                                <template slot="append">米</template>
                            </el-input>

                        </el-form-item>
                    </div>
                    <el-form-item label="是否为长途大车" prop="isLongWayCar">
                        <el-radio-group v-model="vehicleForm.isLongWayCar">
                            <el-radio :label="0">是</el-radio>
                            <el-radio :label="1">否</el-radio>
                        </el-radio-group>
                    </el-form-item>



                    <el-form-item label="货箱结构" prop="structure">
                        <el-checkbox-group v-model="structure" @change="changeStructure">
                            <el-checkbox name="type" :label="item.style" v-for="item in structureArr"
                                :key="item.styleId"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="能源类型" prop="energyType">
                        <el-checkbox-group v-model="energyType" @change="changeEnergyType">
                            <el-checkbox name="type" :label="item.style" v-for="item in energyTypeArr"
                                :key="item.styleId"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="车辆规格" prop="modelType">
                        <el-checkbox-group v-model="modelType" @change="changemodelType">
                            <el-checkbox name="type" :label="item.style" v-for="item in modelTypeArr"
                                :key="item.styleId"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                </el-form>

            </div>
            <div class="footerControlBox">
                <el-button class="cancelBtn" @click="$router.push('/BasicSettings/vehicleConfig')">取消</el-button>
                <el-button class="submitBtn" type="primary" @click="saveData('vehicleForm')">保存</el-button>
            </div>



        </div>






    </div>
</template>
  
<script>
import breadcrumb from "@/components/breadcrumb";
import httpApi from "@/http";
import BASEURL from "@/http/BaseUrl";

export default {
    // 检查 项目名称 是否重复

    data() {
        let simpleNameRule = (rule, value, callback) => {
            let params = {}
            if (this.$route.query.categoryId) {
                params = {
                    categoryId: this.categoryId,
                    simpleName: value
                }
            } else {
                params = {
                    simpleName: value
                }
            }

            httpApi.basicSettingApi.checkCategoryName(params).then(res => {
                if (res.data.code == 200) {
                    callback();
                } else if (res.data.cdoe == 202) {
                    callback(new Error("车型简称已存在"));
                }
            })

        };

        let nameRule = (rule, value, callback) => {
            let params = {}
            if (this.$route.query.categoryId) {
                params = {
                    categoryId: this.categoryId,
                    name: value
                }
            } else {
                params = {
                    name: value
                }
            }

            httpApi.basicSettingApi.checkCategoryName(params).then(res => {
                if (res.data.code == 200) {
                    callback();
                } else if (res.data.cdoe == 202) {
                    callback(new Error("车型名称已存在"));
                }
            })

        };
        let HeightRule = (rule, value, callback) => {

            if (this.heightStart != '' && this.heightEnd != '') {
                if (this.heightStart > this.heightEnd) {
                    callback(new Error("请正确填写车高范围"));
                }


                this.vehicleForm.height = Number(this.heightStart).toFixed(1) + '-' + Number(this.heightEnd).toFixed(1)
                callback();
            } else {
                callback(new Error("请填写车高"));
            }
        };
        let lengthRule = (rule, value, callback) => {
            if (this.lengthStart != '' && this.lengthEnd != '') {
                if (this.lengthStart > this.lengthEnd) {
                    callback(new Error("请正确填写厢长范围"));
                }
                this.vehicleForm.length = Number(this.lengthStart).toFixed(1) + '-' + Number(this.lengthEnd).toFixed(1)
                callback();
            } else {
                callback(new Error("请填写厢长"));
            }
        };
        let loadsRule = (rule, value, callback) => {
            if (this.loadsStart != '' && this.loadsEnd != '') {
                console.log(this.loadsStart, this.loadsEnd);
                if (this.loadsStart > this.loadsEnd) {
                    callback(new Error("请正确填写载重范围"));
                }

                this.vehicleForm.loads = Number(this.loadsStart).toFixed(1) + '-' + Number(this.loadsEnd).toFixed(1)

                callback();
            } else {

                callback(new Error("请填写载重"));
            }
        };
        let capacityRule = (rule, value, callback) => {
            if (this.capacityStart != '' && this.capacityEnd != '') {
                if (this.capacityStart > this.capacityEnd) {
                    callback(new Error("请正确填写载方范围"));
                }
                this.vehicleForm.capacity = Number(this.capacityStart).toFixed(1) + '-' + Number(this.capacityEnd).toFixed(1)
                callback();
            } else {
                callback(new Error("请填写载方"));
            }
        };
        return {
            headers: {
                Authorization: localStorage.getItem("token"),
            },
            categoryId: "",

            lengthStart: "",
            lengthEnd: "",
            capacityStart: "",
            capacityEnd: "",
            loadsStart: "",
            loadsEnd: "",
            heightStart: "",
            heightEnd: "",

            vehicleForm: {
                isLongWayCar: 0,
                image: "",
                simpleName: "",//车辆简称
                name: "",//车辆全称
                energyType: "",
                modelType: "",
                structure: "",
                length: "",
                capacity: "",
                loads: "",
                height: "",
            },
            rules: {
                isLongWayCar: [{ required: true, message: '请选择', trigger: 'change' }],
                image: [{ required: true, message: '请上传', trigger: 'blur' }],
                simpleName: [{ required: true, message: '请填写', trigger: 'blur' }, { required: true, message: '请填写', trigger: 'blur' }, {
                    required: true,
                    validator: simpleNameRule,
                    trigger: "blur",
                }],
                name: [{ required: true, message: '请填写', trigger: 'blur' }, {
                    required: true,
                    validator: nameRule,
                    trigger: "blur",
                }],
                energyType: [{ required: true, message: '请选择', trigger: 'change' }],  //能源类型
                height: [{
                    required: true,
                    validator: HeightRule,
                    trigger: "blur",
                }],
                length: [{
                    required: true,
                    validator: lengthRule,
                    trigger: "blur",
                }],
                loads: [{
                    required: true,
                    validator: loadsRule,
                    trigger: "blur",
                }],
                capacity: [{
                    required: true,
                    validator: capacityRule,
                    trigger: "blur",
                }],
            },
            energyType: [],  //已选的能源类型
            energyTypeArr: [], //所有能源类型可选项
            modelType: [],//规格
            modelTypeArr: [],
            structure: [], //结构
            structureArr: [],


            url: BASEURL.TCHYURL + "/file/upload",

        };
    },
    methods: {
        handleSelectionChange() {

        },
        changePages() {

        },
        handleAvatarSuccess(res) {
            console.log(res);
            this.vehicleForm.image = res.data.url;

            this.$refs["vehicleForm"].clearValidate("image");

        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isPng = file.type === "image/png";
            const isJpeg = file.type === "image/jpeg";

            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isJPG && !isPng && !isJpeg) {
                this.$message.error("上传车辆照片只能是 JPG/png/jpeg 格式!");
                return false;
            }
            if (!isLt5M) {
                this.$message.error("上传车辆照片不能超过 5MB!");
                return false;
            }
            // console.log("条件", (isJPG || isPng || isJpeg) && isLt5M);
            return (isJPG || isPng || isJpeg) && isLt5M;

        },
        async getVehicleEnergyData() {
            let res = await httpApi.basicSettingApi.vehicleEnergyData()
            console.log(res);
            if (res.data.code == 200) {
                this.energyTypeArr = res.data.data.energy
                this.structureArr = res.data.data.container
                this.modelTypeArr = res.data.data.structure
            }


        },
        changemodelType(val) {
            // console.log(val);
            let str = ''
            val.forEach(item => {
                str = str + item + ','
            })
            str = str.slice(0, str.length - 1)
            this.vehicleForm.modelType = str
            // console.log(this.vehicleForm.modelType);
        },
        changeStructure(val) {
            // console.log(val);
            let str = ''
            val.forEach(item => {
                str = str + item + ','
            })
            str = str.slice(0, str.length - 1)
            this.vehicleForm.structure = str
            // console.log(this.vehicleForm.modelType);
        },
        changeEnergyType(val) {
            // console.log(val);
            let str = ''
            val.forEach(item => {
                str = str + item + ','
            })
            str = str.slice(0, str.length - 1)
            this.vehicleForm.energyType = str
         

            this.$refs["vehicleForm"].validateField("energyType", valid => {
                if (valid) {
                    
                } else {
            
                    return false;
                }
            });

            // if (this.energyType.length != 0) {
                
            // }


            // console.log(this.vehicleForm.modelType);
        },

        saveData(formName) {
            this.$refs[formName].validate((valid) => {
                console.log(this.vehicleForm);
                if (valid) {
                    if (this.$route.query.categoryId) {//有id代表编辑车辆
                        this.vehicleForm.categoryId = this.$route.query.categoryId

                        httpApi.basicSettingApi.vehicleConfigEdit(this.vehicleForm).then(res => {
                            if (res.data.code == 200) {
                                this.$message.success('编辑车型成功')
                                this.$router.push('/BasicSettings/vehicleConfig')
                            }
                        })

                    } else {
                        console.log(this.vehicleForm);
                        delete this.vehicleForm.categoryId

                        httpApi.basicSettingApi.vehicleConfigAdd(this.vehicleForm).then(res => {

                            if (res.data.code == 200) {

                                this.$message.success('新增车型成功')
                                this.$router.push('/BasicSettings/vehicleConfig')
                            }
                        })
                    }

                } else {
                    this.$message.error('请填写车型信息')
                    return false;
                }
            });
        },
        async getDetails() {
            let res = await httpApi.basicSettingApi.vehicleConfigDetail({ categoryId: this.$route.query.categoryId })
            if (res.data.code == 200) {
                console.log('回填数据', res.data.data);
                let data = res.data.data
                for (let i in this.vehicleForm) {
                    // console.log(i,'外');
                    for (let key in data) {
                        // console.log(key == i, key);
                        if (key == i) {
                            this.vehicleForm[i] = data[key]
                            break
                        }
                    }


                }

                if (res.data.data.modelType != null) {
                    this.modelType = res.data.data.modelType.split(',')
                }
                if (res.data.data.structure != null) {
                    this.structure = res.data.data.structure.split(',')
                }
                if (res.data.data.energyType != null) {
                    this.energyType = res.data.data.energyType.split(',')
                }
                this.lengthStart = res.data.data.length.split('-')[0]
                this.lengthEnd = res.data.data.length.split('-')[1]

                this.capacityStart = res.data.data.capacity.split('-')[0]
                this.capacityEnd = res.data.data.capacity.split('-')[1]

                this.loadsStart = res.data.data.loads.split('-')[0]
                this.loadsEnd = res.data.data.loads.split('-')[1]

                this.heightStart = res.data.data.height.split('-')[0]
                this.heightEnd = res.data.data.height.split('-')[1]
            }
        },
    },
    created() {
        this.categoryId = this.$route.query.categoryId
        this.getVehicleEnergyData()
        if (this.$route.query.categoryId) {
            this.getDetails()
        }
    },
    mounted() {

    },
    components: {
        breadcrumb,
    },
};
</script>
  
<style lang="scss" scoped>
.main {

    height: calc(100vh - 127px);

    .title {
        background-color: #fff;
        height: 50px;
        font-size: 16px;
        padding: 0 24px;
        line-height: 50px;
        color: #262626;
        border-bottom: 1px solid #f0f0f0;
    }

    .formBox {
        background-color: #fff;
        padding: 36px 36px 0 36px;
        min-height: calc(100vh - 235px);








        .formStyle {
            ::v-deep .el-input__suffix {
                color: #1890FF;
            }

            ::v-deep .el-form-item {
                margin-bottom: 15px;
            }


            ::v-deep .el-form-item__label {
                font-size: 12px;
                color: #262626;
            }

            .layoutBox {
                width: 900px;
                display: flex;
                flex-wrap: wrap;

                .layout {
                    width: 50%;


                    .layout_item {
                        width: 140px;
                        margin: 4px 0;

                    }

                    .layout_middle {
                        margin: 0 8px;
                        color: #262626;
                        font-size: 12px;
                    }
                }

            }


            .picFormItem {
                ::v-deep .el-form-item__content {
                    display: flex;
                }
            }

            .avatar_uploader {
                display: flex;
                width: 240px;
                height: 144px;
                background-color: #f5f5f5;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .prompt {
                margin: 0 0 0 16px;
                color: #949494;
                font-size: 12px;
                min-width: 306px;
                line-height: 20px;
            }

            .picBox {
                margin-left: 20px;
                min-width: 217.5px;
                height: 143.8px;
                border: 1px solid #f0f0f0;
                display: flex;
                justify-content: center;
                align-items: center;

                .pic {
                    height: 81px;
                    width: 165px;
                }

            }



            .VehiclePic {
                width: 240px;
                height: 144px;
                display: flex;
                flex-direction: column;
                justify-content: flex-end;
            }

            .uploadIconBox {

                width: 240px;
                height: 144px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;

                .icon-a- {
                    font-size: 28.7px;
                }

                >.text {
                    color: #1890ff;
                    font-size: 12px;
                    line-height: 0px;
                    margin-top: 10px;
                }
            }
        }


    }

    .footerControlBox {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 60px;
        background-color: #fff;
        margin-top: 14px;

        .cancelBtn {
            width: 80px;
            height: 36px;
            border: 1px solid #d9d9d9;
            color: #262626;
            font-size: 12px;
            border-radius: 4px;
            background-color: #fff;
            margin-right: 16px;
            transition: 0.2;

            &:hover {
                color: #1890ff;
                border-color: #1890ff;

            }
        }

        .submitBtn {
            background-color: #1890ff;
            width: 80px;
            height: 36px;
            color: #fff;
            border-radius: 4px;
            font-size: 12px;
        }

        &:hover {
            opacity: 0.8;
            transition: 0.2;
        }
    }
}
</style>
  